package fr.uvsq.isty.bdh.hchess.engine;

import fr.uvsq.isty.bdh.hchess.gui.game.BoardDisplay;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * A class that listen to the mouse clic and moves to transmit them to the GameData
 * allowing the player to move his pieces.
 * @author Rémi Dubois <RemiEric.Dubois@gmail.com>
 */
public class PieceMoveListener implements MouseListener, MouseMotionListener {
    
    private HumanPlayer player;
    private GameData gameData;
    private BoardDisplay boardDisplay;
    
    /**
     * 
     * @param player the player who will move through this PieceMoveListener
     * @param boardDisplay the BoardDisplay where the mouse input will be caught
     * @param game the GameData to actualise with the movements 
     */
    public PieceMoveListener(HumanPlayer player, BoardDisplay boardDisplay, GameData game) {
        this.player = player;
        gameData = game;
        this.boardDisplay = boardDisplay;
    }
    
    public void mouseClicked(MouseEvent e) {
        // Do nothing
    }
    
    /**
     * Tell the GameData that the plyer tried to pick something on a case determined
     * by the mous position.
     * @param e 
     */
    public void mousePressed(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON1) {
            int caseX = (e.getX()/boardDisplay.getCaseWidth())+1;
            int caseY = 8-(e.getY()/boardDisplay.getCaseHeight());

            gameData.setPick(caseX, caseY, e.getX(), e.getY(), player);
        }
    }
    
    /**
     * Tell the GameData that a piece previously picked have been drop on a case
     * determined by the mouse position.
     * @param e 
     */
    public void mouseReleased(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON1) {
            int caseX = (e.getX()/boardDisplay.getCaseWidth())+1;
            int caseY = 8-(e.getY()/boardDisplay.getCaseHeight());
            
            if (gameData.getPickedPiece() != null) {
                gameData.releasePicked(caseX, caseY, player);
            }
        }
    }

    public void mouseEntered(MouseEvent e) {
        // Do nothing
    }

    public void mouseExited(MouseEvent e) {
        // Do nothing
    }
    
    /**
     * Actualise the positionof the eventualy picked piece in the GameData.
     * @param e 
     */
    public void mouseDragged(MouseEvent e) {
        gameData.setPickedPos(e.getX(), e.getY());
    }

    public void mouseMoved(MouseEvent e) {
        // Do nothing
    }
}
